import React, { useState } from 'react'
import { Modal, Form, Input } from 'antd'

const CustomModal = props => {
  const { children, form, title, record = {}, onAdd, onEdit } = props
  const { getFieldDecorator, validateFields, resetFields } = form
  const [visible, setVisible] = useState(false)

  const showModal = () => {
    setVisible(true)
  }

  const YQCustomModalProps = {
    title,
    visible,
    onCancel: () => setVisible(false)
  }

  const onConfirm = () => {
    validateFields((err, values) => {
      if (!err) {
        if (title === '编辑信息') onEdit(values, record.key)
        if (title === '新增信息') onAdd(values)
        setVisible(false)
        resetFields()
      }
    })
  }

  return (
    <>
      <span onClick={showModal}>{children}</span>
      <Modal {...YQCustomModalProps} onOk={onConfirm}>
        <Form layout="vertical">
          <Form.Item label="用户名" name="name">
            {getFieldDecorator('name', {
              initialValue: record.name,
              rules: [{ required: true, message: 'Please input your name!' }]
            })(<Input placeholder="请输入用户名" />)}
          </Form.Item>
          <Form.Item label="年龄" name="age">
            {getFieldDecorator('age', {
              initialValue: record.age,
              rules: [{ required: true, message: 'Please input your age!' }]
            })(<Input placeholder="请输入年龄" />)}
          </Form.Item>
          <Form.Item label="地址" name="address">
            {getFieldDecorator('address', {
              initialValue: record.address,
              rules: [{ required: true, message: 'Please input your address!' }]
            })(<Input placeholder="请输入地址" />)}
          </Form.Item>
        </Form>
      </Modal>
    </>
  )
}

export default Form.create()(CustomModal)
